//  this library.
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/decoration/mine/image_upload_decoration.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:image_picker/image_picker.dart';

/// 图片上传组件
class ImageUploadWidget extends StatefulWidget {
  const ImageUploadWidget({super.key});

  @override
  State<ImageUploadWidget> createState() => _ImageUploadWidgetState();
}

class _ImageUploadWidgetState extends State<ImageUploadWidget> {
  /// 是否显示图片
  XFile? _xFile;

  /// 图片选择器，必须事先声明才能使用
  late ImagePicker _imagePicker;

  @override
  void initState() {
    super.initState();
    _xFile = null;
    _imagePicker = ImagePicker();
  }

  @override
  Widget build(BuildContext context) {
    return Tooltip(
      // 提示信息
      message: "上传图片，事情说得更明白",
      // 提示框的文本样式
      textStyle: FontUtil.fontWhile1(24),
      // 提示框的装饰样式
      decoration: ImageUploadDecoration(),
      // 提示框的高度
      height: 64,
      // 提示框的内边距
      padding: EdgeInsets.fromLTRB(18, 11, 18, 21),
      // 提示框的外边距
      margin: EdgeInsets.only(left: 28),
      // 提示框显示位置，默认为true：在下面
      preferBelow: false,
      // 提示框的垂直方向的偏移距离
      verticalOffset: 87,
      // 长按或鼠标悬浮超过此值指定的时间后，则显示提示框
      waitDuration: const Duration(seconds: 1),
      // 提示框显示的时长
      showDuration: const Duration(seconds: 2),
      // 子组件
      child: _xFile != null ? _selectedItem() : _defaultItem(),
    );
  }

  /// 默认样式
  _defaultItem() {
    return GestureDetector(
      onTap: _onTapFunImg,
      child: Container(
        width: 100,
        height: 100,
        decoration: BoxDecoration(
          color: colorWhite2,
          borderRadius: BorderRadius.circular(18),
          border: Border.all(color: colorBlack5, width: 1),
        ),
        child: Center(
          child: SvgPicture.asset(
            "images/my/image_upload_icon.svg",
            width: 40,
            height: 40,
          ),
        ),
      ),
    );
  }

  /// 选中样式
  _selectedItem() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(18),
      child: Image.file(
        File(_xFile!.path),
        width: 160,
        height: 160,
        fit: BoxFit.fill,
      ),
    );
  }

  /// 图片点击方法
  _onTapFunImg() async {
    debugPrint("你点击了 ===> 图片选择");
    // 重图库获取单张图片
    XFile? xFile = await _imagePicker.pickImage(source: ImageSource.gallery);
    debugPrint("xFile ===> $xFile");
    debugPrint("xFile2 ===> ${xFile?.path}");
    setState(() {
      _xFile = xFile;
    });
  }
}
